package com.briup.impl.server;

import com.briup.entity.Environment;
import com.briup.impl.util.ConnectionUtil;
import com.briup.inter.server.DBStore;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;


public class DBStoreImplBack2 implements DBStore {
    @Override
    public void saveDB(Collection<Environment> list) throws Exception {
        int lastDay = -1;
        Set<Integer> set = new HashSet<Integer>();
        int count = 0;
        long start = System.currentTimeMillis();
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = ConnectionUtil.getConnection();
            conn.setAutoCommit(false);
            for (Environment e : list) {
                int day = e.getGather_date().toLocalDateTime().getDayOfMonth();
                set.add(day);
                String sql = "insert into table_"+day+"" +
                        "(name, src_id, des_id, dev_id, sensor_address, count, cmd, data, status, gather_date) " +
                        "values(?,?,?,?,?,?,?,?,?,?)";
                if(lastDay == -1){ // 第一条数据
                    ps = conn.prepareStatement(sql);
                    System.out.println("插入的表是table_" + day);
                }else if(day != lastDay){
                    // 处理旧的ps的数据并提交
                    ps.executeBatch();
                    conn.commit();
                    ps.close();
                    count = 0;
                    ps = conn.prepareStatement(sql);
                }
                ps.setString(1, e.getName());
                ps.setString(2, e.getSrcId());
                ps.setString(3, e.getDesId());
                ps.setString(4, e.getDevId());
                ps.setString(5, e.getSersorAddress());
                ps.setInt(6, e.getCount());
                ps.setString(7, e.getCmd());
                ps.setFloat(8, e.getData());
                ps.setInt(9, e.getStatus());
                ps.setTimestamp(10,e.getGather_date());
                ps.addBatch();
                count++;
                if(count % 200 == 0){ // 每200 持久化一次
                    ps.executeBatch();
                    conn.commit();
                }
                lastDay = day;
            }
            ps.executeBatch();
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {}
            e.printStackTrace();
        } finally {
            ConnectionUtil.close(conn,ps);
        }
        long end = System.currentTimeMillis();
        System.out.println("入库成功 时间为" + (end-start) + "毫秒");
        System.out.println("分布的表结构 " + set);
    }
}
